package nl.sweet.testsweet.gui;

import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.AbstractAction;
import javax.swing.JFileChooser;

import nl.sweet.testsweet.TestSweetXMLHandler;

public class SaveToHTMLAction extends AbstractAction
{
	/** Voor serializatie. */
	private static final long serialVersionUID = 1L;

	/** Het resultaat van de unit tests. */
	private TestSweetApplication _app;

	/**
	 * Constructor.
	 * @param app The test sweet application.
	 */
	public SaveToHTMLAction(TestSweetApplication app)
	{
		super("Save to HTML");
		_app = app;
	}

	/**
	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */
	public void actionPerformed(ActionEvent e)
	{
		// Laat een filechooser zien om het resultaat op te slaan.
		JFileChooser fileChooser = new JFileChooser();
		int retVal = fileChooser.showSaveDialog(null);
		if (retVal == JFileChooser.APPROVE_OPTION)
		{
			File outputFile = fileChooser.getSelectedFile();
			if (!outputFile.getName().contains(".html"))
			{
				outputFile = new File(outputFile.getAbsoluteFile() + ".html");
			}
			try
			{
				FileWriter out = new FileWriter(outputFile);
				TestSweetXMLHandler xmlHandler = new TestSweetXMLHandler(
						_app.getTestSweetResults(), _app.getTotalTime());
				xmlHandler.saveHTMLToWriter(out);
				out.close();
			}
			catch (IOException ex)
			{
				ex.printStackTrace();
			}
		}
	}
}
